//
//  SuperInputView.swift
//  自定义输入框
//
//  Created by jin on 2024/9/6.
//

import UIKit
import TangramKit

class SuperInputView : BaseRelativeLayout{
    
    var container:TGLinearLayout!
    
    override func initViews() {
        super.initViews()
        tg_width.equal(.fill)
        tg_height.equal(.wrap)
    }
    
    func initInput() {
        container = ViewFactoryUtil.orientationContainer()
        container.tg_space = PADDING_MEDDLE
        container.tg_gravity = TGGravity.vert.center
        
        addSubview(container)
        
        container.addSubview(iconView)
        container.addSubview(textFieldView)
    }
    
    func bottomBorder() {
        qmui_borderColor = .black90
        qmui_borderPosition = .bottom
    }
    
    func smallBorder() {
        //小圆角，边框
        layer.cornerRadius = SMALL_RADIUS
        layer.borderWidth = 1
        //layer.borderColor = UIColor.colorDivider.cgColor
        layer.borderColor = UIColor.black130.cgColor
        
        //两端有padding
        container.tg_leadingPadding = PADDING_MEDDLE
        container.tg_trailingPadding = PADDING_MEDDLE
    }
    
    @discardableResult
    func passwordStyle() -> SuperInputView {
        textFieldView.isSecureTextEntry = true
        return self
    }
    
    @discardableResult
    func phoneStyle() -> SuperInputView {
        textFieldView.keyboardType = .phonePad
        return self
    }
    
    @discardableResult
    func emailStyle() -> SuperInputView {
        textFieldView.textContentType = .emailAddress
        textFieldView.keyboardType = .asciiCapable
        return self
    }
    
    lazy var iconView: UIImageView = {
        let r = UIImageView()
        r.tg_width.equal(20)
        r.tg_height.equal(20)
        r.tintColor = .black66
        r.image = R.image.inputUsername()!.withTintColor()
        r.hide()
        return r
    }()
    
    lazy var textFieldView: QMUITextField = {
        let r = QMUITextField()
        r.tg_width.equal(.fill)
        r.tg_height.equal(INPUT_MEDDLE)
        r.font = UIFont.systemFont(ofSize: TEXT_LARGE)
        r.textColor = .colorOnSurface
        
        //编辑的时候显示清除按钮
        r.clearButtonMode = .whileEditing
        
        //关闭首字母大写
        r.autocapitalizationType = .none
        return r
    }()
}

//快捷创建方法
extension SuperInputView{
    
    static func input(placeholder:String,image:UIImage?=nil) -> SuperInputView {
        let r = SuperInputView()
        r.initInput()
        
        if let image = image {
            r.iconView.show()
            r.iconView.image = image
        }
        
        r.textFieldView.placeholder = placeholder
        
        r.bottomBorder()
        
        return r
    }
}
